package com;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Mathias
 */
import chat.ChatCommand;
import client.UDPChatClient;
import java.net.*;
import java.io.*;

public class Sender {
    private SocketConfig myCfg = null;
    private UDPChatClient chatClient = null;

    public Sender(SocketConfig myCfg, UDPChatClient chatClient) throws java.net.SocketException {
        this.myCfg = myCfg;
        this.chatClient = chatClient;
    }    
    
    public void send(Serializable data) throws CommunicationException, Exception {
        
        ObjectOutputStream out = null;
        ByteArrayOutputStream bos = null;

        ReliableDatagram relData = new ReliableDatagram();
        int outSequNr = 0;
        if (chatClient.getNickName() != null) {
            outSequNr = chatClient.getSequData().getOutSequNr() + 1;
            chatClient.getSequData().setOutSequNr(outSequNr);
        }
        relData.setSequenceNumber(outSequNr);
        relData.setData(data);
        relData.setLoss(myCfg.getLoss());
        if (relData.packetLost()) {
            System.err.println("[send] msg " + chatClient.getSequData().getOutSequNr() + " for " + myCfg.getServer().toString() + 
                    " lost! cmdType " + ((ChatCommand)data).getCommand());
            return;
        }

        bos = new ByteArrayOutputStream();
         
        try {
            out = new ObjectOutputStream(bos);
            out.writeObject(relData);
            out.close();
        } catch (Exception e) {
             throw e;
        }

        byte[] buf = bos.toByteArray();
                  
        try {
            //System.out.println("sending msg with sequNr" + relData.getSequenceNumber());// + (cmd.getChatMsg() != null ? cmd.getChatMsg().getChatMessage(): " no msg"));
            DatagramPacket packet = new DatagramPacket(buf, buf.length, myCfg.getServer());
            chatClient.getSocket().send(packet);
            
            
        } catch (SocketTimeoutException e) {
            throw new CommunicationException("timeout reached");
         /* catch (Exception e) {
            throw new Exception("Exception in send()", e);
          * */
        }
    }
}
